package org.example.maptovalue;


import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.BinaryOperator;
import java.util.stream.Collectors;


public class MapToValue {

    public static <K, V, C> Map<K, C> convertMapValue(Map<K, V> map,
                                                      BiFunction<K, V, C> valueFunction,
                                                      BinaryOperator<C> mergeFunction) {
        if (isEmpty(map)) {
            return new HashMap<>();
        }
        return map.entrySet().stream().collect(Collectors.toMap(
                e -> e.getKey(),
                e -> valueFunction.apply(e.getKey(), e.getValue()),
                mergeFunction
        ));
    }

    private static <K, V> boolean isEmpty(Map<K,V> map) {
        return map == null || map.isEmpty();
    }

    public static <K, V, C> Map<K, C> convertMapValue(Map<K, V> originMap, BiFunction<K, V, C> valueConverter) {
        return convertMapValue(originMap, valueConverter, MapToValue.pickSecond());
    }

    public static <T> BinaryOperator<T> pickFirst() {
        return (k1, k2) -> k1;
    }

    public static <T> BinaryOperator<T> pickSecond() {
        return (k1, k2) -> k2;
    }

}
